package com.way;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 魏彪
 */
public class Producer extends AbstractProducer {

    private final DataBuffer dataBuffer;

    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    public Producer(DataBuffer dataBuffer) {
        this.dataBuffer = dataBuffer;
    }

    @Override
    protected void produce() {

        synchronized (dataBuffer.getDataBuffer()) {
            while (dataBuffer.getDataBuffer().size() == DataBuffer.MAX_SIZE) {
                try {
                    System.out.println("缓冲区满了，生产者停止生产");
                    dataBuffer.getDataBuffer().wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            dataBuffer.getDataBuffer().add(atomicInteger.getAndIncrement());
            System.out.println("生产者生产了一条数据");

            dataBuffer.getDataBuffer().notifyAll();
        }

    }
}
